import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
import GatherInterface from '@main/entities/service/admin/gather/gather-interface.entity';
import { ApiException } from '@main/common/exceptions/api.exception';
@Injectable()
export class GatherInterfaceService {
  constructor(
    @InjectRepository(GatherInterface)
    private interfaceRepository: Repository<GatherInterface>
  ) {}

  async list() {
    return await this.interfaceRepository.find();
  }

  /**
   * 罗列所有配置
   */
  async page(data) {
    const { pageSize, pageNum, entity = {} } = data;

    const { interfaceName, interfaceCode } = entity;

    return await this.interfaceRepository.findAndCount({
      where: {
        interfaceName: Like(`%${interfaceName}%`),
        interfaceCode: Like(`%${interfaceCode}%`),
      },
      order: {
        updateTime: 'DESC',
      },
      take: pageSize,
      skip: (pageNum - 1) * pageSize,
    });
  }

  /**
   * 新增
   */
  async add(data, user) {
    await this.interfaceRepository.insert({
      ...data,
      createName: user.nickName,
      createUserName: user.userName,
      updateName: user.nickName,
      updateUserName: user.userName,
    });
  }

  /**
   * 更新
   */
  async update(data, user) {
    const { id, remark, interfaceName, interfaceJson } = data;

    await this.interfaceRepository.update(
      { id },
      {
        interfaceName,
        interfaceJson,
        remark,
        updateName: user.nickName,
        updateUserName: user.userName,
      }
    );
  }

  /**
   * 删除
   */
  async delete(idList) {
    await this.interfaceRepository.delete(idList);
  }

  async isExistKey(data) {
    const { interfaceCode } = data;

    const result = await this.interfaceRepository.findOne({
      where: { interfaceCode },
    });

    if (result) {
      throw new ApiException(10041);
    }
  }
}
